package tools;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;

/**
 * Created by yangxianming on 2017/6/16.
 * 动态写配置
 */
public class WriteProperties {
    //增加 或 覆盖一个键值
    public static void addKV(String path, String key, String value) throws Exception{
        //获取系统名字
        String splitMark = "\\";
        if (!System.getProperty("os.name").contains("Windows")){
            splitMark = "/";
        }
        String propPath = path + splitMark + "config" + splitMark + "app.properties";
        Properties properties = new Properties();

        properties.load(new FileInputStream(propPath));
        properties.setProperty(key, value);
        FileOutputStream fileOutputStream = new FileOutputStream(propPath);
        properties.store(fileOutputStream, "");
    }

    //对一条配置添加一个元素
    public static void addElement(String path, String key, String value) throws Exception{
        //获取系统名字
        String splitMark = "\\";
        if (!System.getProperty("os.name").contains("Windows")){
            splitMark = "/";
        }
        String propPath = path + splitMark + "config" + splitMark + "app.properties";
        Properties properties = new Properties();

        properties.load(new FileInputStream(propPath));
        String old = properties.getProperty("jmeterNodeAddress");
        properties.setProperty(key, old + "," + value);
        FileOutputStream fileOutputStream = new FileOutputStream(propPath);
        properties.store(fileOutputStream, "");
    }
    public static void removeElement(String path, String key, String removeElement) throws Exception{
        //获取系统名字
        String splitMark = "\\";
        if (!System.getProperty("os.name").contains("Windows")){
            splitMark = "/";
        }
        String propPath = path + splitMark + "config" + splitMark + "app.properties";
        Properties properties = new Properties();

        properties.load(new FileInputStream(propPath));
        String[] old = properties.getProperty("jmeterNodeAddress").split(",");
        ArrayList<String> arrOld = new ArrayList<String>();
        Collections.addAll(arrOld, old);
        if (arrOld.contains(removeElement)){
            arrOld.remove(removeElement);
            String strOld = String.join(",", arrOld);
            properties.setProperty(key, strOld);
            FileOutputStream fileOutputStream = new FileOutputStream(propPath);
            properties.store(fileOutputStream, "");
        }
    }
}
